#ifndef __LOG_HPP__
#define __LOG_HPP__

#include <iostream>
#include <unistd.h>
#include <string>
#include <filesystem>
#include <cstdio>
#include <memory>
#include <ctime>
#include <sstream>
#include <fstream>
#include "Mutex.hpp"
using namespace std;

const string gresp = "\r\n";

class LogStrategy
{
public:
    ~LogStrategy() {}
    virtual void SyncLog(const string &message) = 0;
};

class ConsoleLogStrategy : public LogStrategy
{
public:
    ConsoleLogStrategy()
    {
    }

    void SyncLog(const string &messages)
    {
        LockGuard lockguard(_mutex);
        cout << messages << gresp;
    }

    ~ConsoleLogStrategy()
    {
    }

private:
    Mutex _mutex;
};

const string defaultpath = "./log";
const string defaultfile = "my.log";

class FileLogStrategy : public LogStrategy
{
public:
    FileLogStrategy(const string &path = defaultpath, const string &file = defaultfile)
        : _path(path), _file(file)
    {
        LockGuard lockguard(_mutex);
        if (filesystem::exists(_path))
        {
            return;
        }
        try
        {
            filesystem::create_directories(_path);
        }
        catch (const filesystem::filesystem_error &e)
        {
            cerr << e.what() << endl;
        }
    }
    void SyncLog(const string &messages)
    {
        LockGuard lockguard(_mutex);

        string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
        ofstream out(filename, ios::app);
        if (!out.is_open())
        {
            return;
        }
        out << messages << gresp;
        out.close();
    }

private:
    string _path;
    string _file;
    Mutex _mutex;
};

enum LogLevel
{
    DEBUG,
    INFO,
    WARNING,
    FATAL,
    ERROR
};
string Levelstr(LogLevel level)
{
    switch (level)
    {
    case LogLevel::DEBUG:
        return "DEBUG";
    case LogLevel::INFO:
        return "INFO";
    case LogLevel::WARNING:
        return "WARNING";
    case LogLevel::FATAL:
        return "FATAL";
    case LogLevel::ERROR:
        return "ERROR";
    default:
        return "UNKNOWN";
    }
}
string GettimeStamp()
{
    time_t curr = time(nullptr);
    struct tm curr_m;
    localtime_r(&curr, &curr_m);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d-%02d-%02d",
             curr_m.tm_year + 1900,
             curr_m.tm_mon + 1,
             curr_m.tm_mday,
             curr_m.tm_hour,
             curr_m.tm_min,
             curr_m.tm_sec);
    return buffer;
}

class Logger
{
public:
    Logger()
    {
        EnableConsoleLogStrategy();
    }

    void EnableFileLogStrategy()
    {
        _fflush_strategy = make_unique<FileLogStrategy>();
    }

    void EnableConsoleLogStrategy()
    {
        _fflush_strategy = make_unique<ConsoleLogStrategy>();
    }

    class LogMessage
    {
    public:
        LogMessage(LogLevel &level, string &src_name, int line_num, Logger &logger)
            : _curr_time(GettimeStamp()), _line_num(line_num), _pid(getpid()), _src_name(src_name), _level(level), _log(logger)
        {
            stringstream ss;
            ss << "[" << _curr_time << "]"
               << "[" << Levelstr(_level) << "]"
               << "[" << _pid << "]"
               << "[" << _src_name << "]"
               << "[" << _line_num << "]"
               << "-";
            _log_info = ss.str();
        }

        template <typename T>
        LogMessage &operator<<(const T &info)
        {
            stringstream ss;
            ss << info;
            _log_info += ss.str();
            return *this;
        }

        ~LogMessage()
        {
            if (_log._fflush_strategy)
            {
                _log._fflush_strategy->SyncLog(_log_info);
            }
        }

    private:
        string _curr_time;
        int _line_num;
        pid_t _pid;
        string _src_name;
        string _log_info;
        LogLevel _level;
        Logger &_log;
    };

    LogMessage operator()(LogLevel level, string name, int line)
    {
        return LogMessage(level, name, line, *this);
    }

    ~Logger()
    {
    }

private:
    unique_ptr<LogStrategy> _fflush_strategy;
};

Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
#define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()

#endif